import type { Module } from "vuex";
import type { RootState } from "../types";
import request from "@/public/request";
import type { MenuTree } from "@/types/menu";


/**
 * 菜单相关state
 */
export interface MenuState {
  /**
   * 是否是用外部的菜单
   */
  isExternalWorkbench: boolean;
  // 菜单map
  menuMap: Map<string, any[]>;
  
}
export interface PathButtonsPayload {
  code: string;
  path: string;
  callback(result: boolean): void;
}

function fillButtonsToMap(map:Map<string,string[]>,item:any){
  map.set(item.Path.toLowerCase(),item.Buttons);
  for(let child of item.Children){
      fillButtonsToMap(map,child);
  }
}



const module: Module<MenuState, RootState> = {
  namespaced: true,
  state: {
    /**
     * 是否是到外部的
     */
    isExternalWorkbench: true,
    menuMap: new Map<string, any[]>(),
    
  },
  getters: {
    // 工作台路径
    workbenchPath: (state) => {
      return "/internal";
    },
    // 用户设置路径
    userSettingPath:(state)=>{
      if (state.isExternalWorkbench) {
        return "/workbench/userSetting";
      } else {
        return "/internal/userSetting";
      }
    }
  },
  mutations: {
    /**
     * 设置是否是用外部的菜单
     * @param state
     * @param value
     */
    setMenuMap(state, map) {
      state.menuMap = map;
    },

  },
  actions: {
    /**
     * 获得当前用户菜单 判断是否是外部菜单
     * @param param0
     */
    async getCurrentEmployeeMenuTree({ commit,dispatch }) {
      let menus = await request.get("/api/menu/build");
      let allMenus=[{
        name: "工作中心",
        path: "/internal/home",
        children:[],
        meta:{
          title:"工作中心"
        }
      },...menus]
      allMenus.forEach((item)=>{
        item.visible = false
      })
      // await dispatch("initMenu",menus)
      return allMenus;

    },

    initMenu({ commit, state }, menuTree: any[]) {
      let map = new Map<string, string[]>();

      for (let item of menuTree) {
        fillButtonsToMap(map, item);
      }
      commit("setMenuMap", map);
    },
    /**
     * 获得这个路径下的按钮 是否是被授权的
     * @param param0 
     * @param payload 
     */
     getPathButtons({state},payload:PathButtonsPayload){
      let v = state.menuMap.get(payload.path.toLocaleLowerCase())
      if(v && v.find(t=>t.Code == payload.code)){
        return true;
      }else{
        return false;
      }

    }
  },
};

export default module;
